package cn.lastjune.util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExcelUtil {
	
	public ExcelUtil() {
		super();
	}
	/**
	 * @param datas
	 *            封装着Object[]的列表, 一般是String内容.
	 * @param title
	 *            每个sheet里的标题.
	 * @throws Exception 
	 */
	public static void writeExcel(OutputStream out, List datas, String[] title) throws Exception {
		if (datas == null) {
			throw new IllegalArgumentException("写excel流需要List参数!");
		}
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(out);
			WritableSheet ws = workbook.createSheet("sheet 1", 0);
			int rowNum = 0; // 要写的行
			if (title != null) {
				putRow(ws, 0, title);// 压入标题
				rowNum = 1;
			}
			for (int i = 0; i < datas.size(); i++, rowNum++) {// 写sheet
				Object[] cells = (Object[]) datas.get(i);
				putRow(ws, rowNum, cells); // 压一行到sheet
			}

			workbook.write();
			workbook.close(); // 一定要关闭, 否则没有保存Excel
		}  catch (IOException e) {
			System.out.println("jxl write file i/o exception!, cause by: "
					+ e.getMessage());
		}
	}
	private static void putRow(WritableSheet ws, int rowNum, Object[] cells) throws Exception{
        for(int j=0; j<cells.length; j++) {//写一行
            Label cell = new Label(j, rowNum, ""+cells[j]);
            ws.addCell(cell);
        }
    }
}
